package psn.kiko.service.database.ddl;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Connection;

/**
 * 执行sqlScriptName.sql文件
 */
@Service
@Slf4j
public class SQLScriptExecutorService {
	private SqlSessionFactory sqlSessionFactory;
	@Autowired
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	
	/**
	 * 执行指定的sql脚本文件
	 * @param sqlFilePath 文件路径
	 */
	public void runScript(String sqlFilePath) throws IOException {
		log.debug("运行的sql脚本文件路径：{}",sqlFilePath);
		try ( SqlSession sqlSession = sqlSessionFactory.openSession( ) ) {
			Connection connection = sqlSession.getConnection( );
			ScriptRunner scriptRunner = new ScriptRunner(connection);
			scriptRunner.setLogWriter(null);
			scriptRunner.runScript(Resources.getResourceAsReader(sqlFilePath));
		}
	}
}
